/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.sys.user.web;

//import cn.knet.agent.domain.UserAccount;
import cn.knet.sp.ncrm.common.beanvalidator.BeanValidators;
import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.utils.DateUtils;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.utils.excel.ExportExcel;
import cn.knet.sp.ncrm.common.utils.excel.ImportExcel;
import cn.knet.sp.ncrm.common.vo.JsonResultMap;
import cn.knet.sp.ncrm.common.web.BaseController;

import cn.knet.sp.ncrm.modules.customer.importsupport.ImportService;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.entity.PotentialCustomer;
import cn.knet.sp.ncrm.modules.customer.potentialcustomer.service.PotentialCustomerService;
import cn.knet.sp.ncrm.modules.sys.office.entity.Office;
import cn.knet.sp.ncrm.modules.sys.role.entity.Role;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.user.service.SystemService;
import cn.knet.sp.ncrm.modules.sys.utils.CallUtils;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;
//import com.cintel.ws.cc.wsdl.v1_0.agent._interface.AgentService;
//import com.cintel.ws.cc.wsdl.v1_0.agent.model.AgentContext;
//import com.cintel.ws.cc.wsdl.v1_0.agent.model.AgentFuncConfig;
//import com.cintel.ws.cc.wsdl.v1_0.agent.model.AgentInfo;
//import com.cintel.ws.cc.wsdl.v1_0.agent.service.AgentWsLocator;
//import com.cintel.ws.cc.wsdl.v1_0.extension._interface.ExtensionService;
//import com.cintel.ws.cc.wsdl.v1_0.extension.model.ConferenceType;
//import com.cintel.ws.cc.wsdl.v1_0.extension.model.ExtensionContext;
//import com.cintel.ws.cc.wsdl.v1_0.extension.model.ExtensionType;
//import com.cintel.ws.cc.wsdl.v1_0.extension.service.ExtensionWsLocator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.xml.rpc.ServiceException;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 *
 * @author ThinkGem
 * @version 2013-8-29
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private ImportService importService;


    @ModelAttribute
    public User get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return systemService.getUser(id);
        } else {
            return new User();
        }
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = {"index"})
    public String index(User user, Model model) {
        return "modules/sys/user/userIndex";
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = {"list", ""})
    public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<User> page = systemService.findUser(new Page<User>(request, response), user);
        model.addAttribute("page", page);
        return "modules/sys/user/userList";
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "form")
    public String form(User user, Model model) {
        if (user.getCompany() == null || user.getCompany().getId() == null) {
            user.setCompany(UserUtils.getUser().getCompany());
        }
        if (user.getOffice() == null || user.getOffice().getId() == null) {
            user.setOffice(UserUtils.getUser().getOffice());
        }
        model.addAttribute("user", user);
        if (UserUtils.getUser().isAdmin()) {
            model.addAttribute("allRoles", systemService.findAllRole());
        } else {
            model.addAttribute("allRoles", UserUtils.getUser().getRoleList());
        }
        model.addAttribute("allNos", systemService.findAllInvalidNo());
        return "modules/sys/user/userForm";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "save")
    public String save(User user, String isknet, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes)
            throws Exception {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }

//        UserAccount userAccount = UserUtils.getUserAccount(user.getLoginName());
//        logger.info("捉虫已经存在该用户名，useraccount={}", userAccount);
//        if (userAccount != null && isknet == null && StringUtils.isBlank(user.getId())) {
//            addMessage(model, "用户：" + userAccount.getUsername() + "，姓名:" + userAccount.getName() + "，email:" + userAccount.getEmail() + " 中网账号体系已经存在，确认使用这个账号？");
//            model.addAttribute("knetuser", true);
//            UserUtils.clearCache(user);
//            return form(user, model);
//        }
//        String knetId = null;
//        if (isknet != null) {
//            if (isknet.equals("true")) {
//                // 添加角色
//                UserUtils.saveNcrmRole(userAccount.getUsername(), user.getLoginFlag());
//                knetId = userAccount.getId();
//
//            } else if (isknet.equals("false")) {
//                if(userAccount == null) {
//                    //添加用户
//                    knetId = UserUtils.saveUserAccount(user);
//                } else {
//                    addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
//                    return form(user, model);
//                }
//            }
//        }
//
//        //登陆用户在捉虫和ncrm都不存在
//        if (userAccount == null && isknet == null) {
//            knetId = UserUtils.saveUserAccount(user);
//        }
//        //使用捉虫系统用户id
//        if (StringUtils.isNotBlank(knetId)){
//            user.setId(knetId);
//        }

        // 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
        user.setCompany(new Office(request.getParameter("company.id")));
        user.setOffice(new Office(request.getParameter("office.id")));
//        if (user.getNo() !=null && !user.getNo().matches("^[1-9][0-9]{1,4}$")){
//            addMessage(model, "保存用户'" + user.getNo() + "'失败，工号不符合规则");
//            return form(user, model);
//        }
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
        } else {
            user.setPassword(SystemService.entryptPassword("abc123"));
        }
        if (!beanValidator(model, user)) {
            return form(user, model);
        }
        if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))) {
            addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
            return form(user, model);
        }
        // 角色数据有效性验证，过滤不在授权内的角色
        List<Role> roleList = Lists.newArrayList();
        List<String> roleIdList = user.getRoleIdList();
        for (Role r : systemService.findAllRole()) {
            if (roleIdList.contains(r.getId())) {
                roleList.add(r);
            }
        }
        user.setRoleList(roleList);
        // 保存用户信息
        systemService.saveUser(user);

        //同步创建呼叫中心账号,新增或修改用户时,同时新增或修改分机和坐席
        if(Global.getConfig("create.callcenter.no").equals("true")) {
            CallUtils.createCallCenterNo(user, redirectAttributes);
        }

        // 清除当前用户缓存
        if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
            UserUtils.clearCache();
            //UserUtils.getCacheMap().clear();
        }
        addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");

        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "delete")
    public String delete(User user, RedirectAttributes redirectAttributes) throws Exception {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        if (UserUtils.getUser().getId().equals(user.getId())) {
            addMessage(redirectAttributes, "删除用户失败, 不允许删除当前用户");
        } else if (User.isAdmin(user.getId())) {
            addMessage(redirectAttributes, "删除用户失败, 不允许删除超级管理员用户");
        } else {
            UserUtils.removeNcrmRole(user.getLoginName());
            systemService.deleteUser(user);
            //删除用户时,将坐席名称重置为空
            if(Global.getConfig("create.callcenter.no").equals("true")) {
                CallUtils.resetAgentName(user, redirectAttributes);
            }
            //删除用户时,回收用户数据
            importService.recoverByUserId(user.getId());
            addMessage(redirectAttributes, "删除用户成功");
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 导出用户数据
     *
     * @param user
     * @param request
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
            new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, request, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "deletes")
    @ResponseBody
    public String deletes(@RequestParam(value = "ids[]", defaultValue = "") String[] ids, RedirectAttributes redirectAttributes) throws Exception {
        JsonResultMap jsonResultMap = JsonResultMap.getJsonResultMap(true);
        if (Global.isDemoMode()) {
            jsonResultMap.addErrorMessage("演示模式，不允许操作！");
        }
        for (String id : ids) {
            if (UserUtils.getUser().getId().equals(id)) {
                jsonResultMap.addErrorMessage("删除用户失败, 不允许删除当前用户");
            } else if (User.isAdmin(id)) {
                jsonResultMap.addErrorMessage("删除用户失败, 不允许删除超级管理员用户");
            } else {
                User u = UserUtils.get(id);
                if (u != null) {
                    UserUtils.removeNcrmRole(u.getLoginName());
                    systemService.deleteUser(u);
                    //删除用户时,将坐席名称重置为空
                    if(Global.getConfig("create.callcenter.no").equals("true")) {
                        CallUtils.resetAgentName(u, redirectAttributes);
                    }
                    //删除用户时,回收用户数据
                    importService.recoverByUserId(u.getId());
                    jsonResultMap.addMessage("删除用户成功");
                }

            }
        }
        return jsonResultMap.toJson();
        //return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 导入用户数据
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importsFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/user/list?repage";
        }
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<User> list = ei.getDataList(User.class);
            for (User user : list) {
                try {
                    if(null==user || !user.getNo().matches("^[0-9]{0,8}$") ){
                        failureMsg.append("<br/>工号必须为数字不能为空,并且长度为1至8位 ");
                        failureNum++;
                        continue;
                    }
                    if ("false".equals(checkNo("", user.getNo()))) {
                        failureMsg.append("<br/>工号 " + user.getNo() + " 已存在; ");
                        failureNum++;
                        continue;
                    }
                    if ("true".equals(checkLoginName("", user.getLoginName()))) {
                        user.setPassword(SystemService.entryptPassword("abc123"));
                        BeanValidators.validateWithException(validator, user);
                        if (!UserUtils.isKnetUser(user.getLoginName())) {
                            UserUtils.saveUserAccount(user);
                        } else {
                            UserUtils.saveNcrmRole(user.getLoginName(), "1");
                        }
                        systemService.saveUser(user);
                        successNum++;
                    } else {
                        failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; ");
                        failureNum++;
                    }

                } catch (ConstraintViolationException ex) {
                    logger.error(ex.getMessage(), ex);
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList) {
                        failureMsg.append(message + "; ");
                        failureNum++;
                    }
                } catch (Exception ex) {
                    logger.error(ex.getMessage(), ex);
                    failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败：" + ex.getMessage());
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条用户，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条用户" + failureMsg);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            addMessage(redirectAttributes, "导入用户失败！");
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 下载导入用户数据模板
     *
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据导入模板.xlsx";
            List<User> list = Lists.newArrayList();
            list.add(UserUtils.getUser());
            new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, request, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + adminPath + "/sys/user/list?repage";
    }

    /**
     * 验证登录名是否有效
     * 2015年7月7日 增加捉虫登陆用户验证
     *
     * @param oldLoginName
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName != null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName != null && systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }

    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkNo")
    public String checkNo(String oldNo, String no) {
        if (no != null && no.equals(oldNo)) {
            return "true";
        } else if (no != null && systemService.getUserByNo(no) == null) {
            return "true";
        }
        return "false";
    }

    /**
     * 用户信息显示及保存
     *
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "info")
    public String info(User user, HttpServletResponse response, Model model) {
        User currentUser = UserUtils.getUser();
        if (StringUtils.isNotBlank(user.getName())) {
            if (Global.isDemoMode()) {
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/userInfo";
            }
            currentUser.setEmail(user.getEmail());
            currentUser.setPhone(user.getPhone());
            currentUser.setMobile(user.getMobile());
            currentUser.setRemarks(user.getRemarks());
            currentUser.setPhoto(user.getPhoto());
            systemService.updateUserInfo(currentUser);
            model.addAttribute("message", "保存用户信息成功");
        }
        model.addAttribute("user", currentUser);
        model.addAttribute("Global", new Global());
        return "modules/sys/user/userInfo";
    }

    /**
     * 返回用户信息
     *
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "infoData")
    public User infoData() {
        return UserUtils.getUser();
    }

    /**
     * 修改个人用户密码
     *
     * @param oldPassword
     * @param newPassword
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "modifyPwd")
    public String modifyPwd(String oldPassword, String newPassword, Model model) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
            if (Global.isDemoMode()) {
                model.addAttribute("message", "演示模式，不允许操作！");
                return "modules/sys/user/userModifyPwd";
            }
            if (SystemService.validatePassword(oldPassword, user.getPassword())) {
                systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                model.addAttribute("message", "修改密码成功");
            } else {
                model.addAttribute("message", "修改密码失败，旧密码错误");
            }
        }
        model.addAttribute("user", user);
        return "modules/sys/user/userModifyPwd";
    }

    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = systemService.findUserByOfficeId(officeId);
        for (int i = 0; i < list.size(); i++) {
            User e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "u_" + e.getId());
            map.put("pId", officeId);
            map.put("name", StringUtils.replace(e.getName(), " ", ""));
            mapList.add(map);
        }
        return mapList;
    }

//	@InitBinder
//	public void initBinder(WebDataBinder b) {
//		b.registerCustomEditor(List.class, "roleList", new PropertyEditorSupport(){
//			@Autowired
//			private SystemService systemService;
//			@Override
//			public void setAsText(String text) throws IllegalArgumentException {
//				String[] ids = StringUtils.split(text, ",");
//				List<Role> roles = new ArrayList<Role>();
//				for (String id : ids) {
//					Role role = systemService.getRole(Long.valueOf(id));
//					roles.add(role);
//				}
//				setValue(roles);
//			}
//			@Override
//			public String getAsText() {
//				return Collections3.extractToString((List) getValue(), "id", ",");
//			}
//		});
//	}
}
